//1. 引入express模块
const express = require("express");
// 引入https,用于发送请求
const https = require("https");
const fs = require("fs");
const path = require("path");
// 获取启动方式: dev本地开发模式 pro生产模式 默认本地开发模式
const mode = process.argv[2] || 'dev';
// 引入数据库工具类
const {
    query
} = require("./db/index");
// 导入配置信息
const config = require("./config");
// 引入body-parser 设置json解析的大小限制
const bodyParser = require("body-parser");
//3. 引入跨域模块
const cors = require("cors");
//5. 引入token解析模块
const expressJWT = require("express-jwt");
require("./componets/article");
//6. 引入工具模块
const {
    format,
    getAddress,
    isEmpty
} = require("./utils/index");
//7. 引入日志模块
const {
    errM,
    insertLogInfo
} = require("./utils/log-tools");
//8. 引入路由模块
const adminRouter = require("./router/admin/admin");
const articleManageRouter = require("./router/admin/article_manage");
const article = require("./router/public/article");
const PORT = 3333;
const IP = "127.0.0.1";


// 设置secretKey
const secretKey = config.jwtSecretKey;

const app = express();

// 获取ssl证书
const options = {
    key: fs.readFileSync(path.join(process.cwd(), '/configs','/ssl','/cemcode.com.key')),
    cert: fs.readFileSync(path.join(process.cwd(), './configs','/ssl','/cemcode.com_bundle.crt'))
}

// 引入中间件
app.use(cors());
// 放宽大小
app.use(bodyParser.json({
    "limit": "2mb"
}))
app.use(expressJWT({
    secret: secretKey,
    algorithms: ["HS256"]
}).unless({
    path: [/^\/admin\/api\/login/, /^\/public\//]
}));
app.use(express.json());
app.use(express.urlencoded({
    extended: true
}));
app.use((req, res, next) => {
    let ip = req.socket.remoteAddress;
    if(ip.indexOf(":")!=-1){
        ip = req.socket.remoteAddress.match(/:([^:\s]*)$/)[1];
    }
    const obj = {
        address: "",
        url: req.url,
        create_time: Date.now(),
        ip,
    }
    console.log(`${format(Date.now())} - ${ip} - ${req.url}`);
    const sql_insert = `insert into t_request_log (url,address,create_time,ip) values(?,?,?,?)`;

    function tempSQLFUN() {
        query(sql_insert, [obj.url, obj.address, obj.create_time, obj.ip]).then(result => {
            if (result.affectedRows !== 1) {
                insertLogInfo(0, "插入request失败");
            }
        }).catch(err => {
            insertLogInfo(0, err);
        })
    }

    req.request_ip = ip;
    if (isEmpty(ip)) {
        obj.address = "空"
        req.request_address = "空";
        tempSQLFUN();
    } else if (ip === "1" || ip === "127.0.0.1") {
        obj.address = "局域"
        req.request_address = "局域";
        tempSQLFUN();
    } else {
        getAddress(ip).then((result)=>{
                obj.address = result;
                tempSQLFUN();
        }).catch(err=>{
            insertLogInfo(0, err)
        })
    }
    next();
})
app.use(errM);

// 注册路由中间件
app.use("/admin/api", adminRouter);
app.use("/public/api", article);
app.use("/article_manage/api", articleManageRouter);

app.use(errM);
// 生产模式
if ('pro' == mode) {
    https.createServer(options, app).listen(PORT);
} else if ('dev' == mode) { // 开发模式
    app.listen(PORT, () => {
        console.log(`server run , ip: ${IP}:${PORT}`);
    })
} else { // 未知
    console.log("模式未知请重新启动");
}
